// packageA/pages/equipmentStockList/equipmentStockList.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:{},
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //状态
    valState:-1,
    //状态选项
    optionsState:[{
      value: -1,
      text: "所有状态",
    },{
      value: 1,
      text: "待验收",
    },{
      value: 2,
      text: "待保养",
    },{
      value: 3,
      text: "待检测",
    },{
      value: 4,
      text: "已完成",
    },{
      value: 5,
      text: "已核算",
    },{
      value: 6,
      text: "已预订",
    },{
      value: 7,
      text: "已出库",
    }],
    //搜索关键词
    searchValue:'',
    //仓库
    depot:{
      id:null,
      name:'请选择仓库'
    },
    //仓库选择框
    showDepot:false,
    //仓库选择数据
    depotList:[],
    //搜索仓库
    valueSearchDepot:'',
    //设备类型选择框
    showType:false,
    //选择的设备类型id
    typeIds: [],
    //选择的设备类型名字
    typeNames: '请选择设备类型'  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取列表数据
    this.getList();

    this.setData({
      authority:app.globalData.authority
    })
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let dataObj={
      type: 1,
      selectFields: ["id","equipmentNo","imei","type", "state", "num","category", "createDate", "name", "spec","unit","depot","relationOrderNo","leaseRecord","ioStorageDetail","performance","remarks","checkRecord","maintain","testRecord","checkRemarks","orderObj","service","keepAccounts","dataAuthority","appId","accountingPrice"],
      sort: {
        id: -1
      },
      page: {
        page: this.data.page,
        pageSize: 10
      }
    } 

    //搜索设备编码
    if(this.data.searchValue){
      dataObj.equipmentNo='%' +this.data.searchValue+ '%';
    }

    //设备类型
    if(this.data.typeIds && this.data.typeIds.length){
      dataObj.category=this.data.typeIds;
    }

    //仓库
    if(this.data.depot.id){
      dataObj['depot.id']=this.data.depot.id;
    }

    //状态
    if(this.data.valState!=-1){
      dataObj.state=this.data.valState;
    }
    
    let param = {
      isAuth: true,
      className: 'repertory',
      data: dataObj
    }

    CommonService.goFindList(param).then(res => {
      Toast.clear();
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;

        result.forEach(item => {
          //状态
          switch(item.state){
            case 1:
              item.stateWord='待验收';
              item.stateClass='c-4';
              break;
            case 2:
              item.stateWord='待保养';
              item.stateClass='c-7';
              break;
            case 3:
              item.stateWord='待检测';
              item.stateClass='c-2';
              break;
            case 4:
              item.stateWord='已完成';
              item.stateClass='c-1';
              break;
            case 5:
              item.stateWord='已核算';
              item.stateClass='c-5';
              break;
            case 6:
              item.stateWord='已预订';
              item.stateClass='c-4';
              break;
            case 7:
              item.stateWord='已出库';
              item.stateClass='c-6';
              break;
          }     
        });

        console.log('设备库存列表');
        console.log(result);

        this.setData({
          list: this.data.list.concat(result)
        })
      }else{
        this.setData({
          notMore: false
        })
        if(this.data.page==1){
          this.setData({
            showNothing: true
          })
        }else{
          Toast.fail('没有更多了');
        }
      }
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
    })
  },  

  //状态筛选
  onChangeState({detail}){
    this.setData({ 
      valState: detail
    }) 
    this.refreshListAndPage();
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
  },
  
  //刷新筛选
  refreshListAndPage2(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false,
      searchValue: '',
      depot:{
        id:null,
        name:'请选择仓库'
      },
      typeIds: [],
      typeNames: '请选择设备类型',
      valState: -1
    })
    this.getList();
  },
  
  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value,
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //显示仓库
  onShowDepot(){
    this.setData({
			showDepot: true
    })
    this.getDepotList();
  },

  //查询仓库
  getDepotList(){
    this.setData({
      depotList: []
    })

    let param = {
      isAuth: false,
      className: 'partsDepots',
      data: {
        searchAll: true,
        selectFields: ['id','name']
      }
    }

    //模糊查询
    if(this.data.valueSearchDepot){
      param.data.name='%' + this.data.valueSearchDepot + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id
          });
        });
        this.setData({
          depotList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //隐藏仓库
  onCloseDepot(){
    this.setData({
      showDepot: false,
      valueSearchDepot:''
    })  
    this.refreshListAndPage();
  },

  //确认仓库
  onConfirmDepot(e){ 
    let id='depot.id';
    let name='depot.name';
    this.setData({
      [id]:e.detail.value.id,
      [name]:e.detail.value.text
    })
    
    this.onCloseDepot();
  },

  //搜索仓库
  onChangeDepotVal(e){
    this.setData({
      valueSearchDepot: e.detail
    })
    this.getDepotList();
  },

  //清除仓库选择
  onCancelDepot(){
    let id='depot.id';
    let name='depot.name';
    this.setData({
      [id]:null,
      [name]:'请选择仓库'
    })
    this.onCloseDepot();
  },

  //显示设备类型选择框
  onShowType(){
    this.setData({
			showType: true
    })
    //查询一级
    this.findEquipmentCategory();
  },

  //隐藏设备类型选择框
  onCloseType(){
    this.setData({
			showType: false
    })
    this.refreshListAndPage();
  },

  //选择设备类型
  onChangeType(event) {
    const { picker, value, index } = event.detail;
    let arr=picker.getValues();
    this.findChildren(arr[0].id);
  },

  //确认设备类型
  onConfirmType(e){
    let arr=e.detail.value;
    let idArr=[],nameArr=[];

    arr.forEach(item => {
      if(item){
        idArr.push(item.id);
        nameArr.push(item.text);
      }
		});

    this.setData({
      typeIds: idArr,
      typeNames: nameArr.join(' - '),
    })
    this.onCloseType();
  },

  //清除设备类型选择
  onCancelType(){
    this.setData({
      typeIds:null,
      typeNames:'请选择设备类型'
    })
    this.onCloseType();
  },

  //查询设备一级分类
  findEquipmentCategory(){
    let param = {
      isAuth: false,
      className: 'equipmentCategory',
      data: {
        searchAll: true,
        fid: 1,
        selectFields: ["id", "fid", "name"],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let cateArr=[];
        result.forEach(item => {
          cateArr.push({
            id:item.id,
            text:item.name,
          });
        });
        this.setData({
          typeOne: cateArr
        })
        //查询子分类
        this.findChildren(result[0].id);
      }
    }).catch((error) => {
    })
  },

  //查询子分类
  findChildren(fid){
    let param = {
      isAuth: false,
      className: 'equipmentCategory',
      data: {
        searchAll: true,
        fid: fid,
        selectFields: ["id", "fid", "name"],
        nbl:Base64.encode(util.timeFormatDay(new Date())),
      }
    }

    CommonService.goFindList(param).then(res=>{
      let typeOne=this.data.typeOne;
      //处理分类数据格式
      let typeList=[{
        values: typeOne,
        className: 'column1'
      }]

      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let cateArr=[];
        result.forEach(item => {
          cateArr.push({
            id:item.id,
            text:item.name,
          });
        });
        typeList.push({
          values: cateArr,
          className: 'column2'
        });
      }else{
        typeList.push({
          values: [],
          className: 'column2'
        });
      }

      this.setData({
        typeList: typeList
      })
    }).catch((error) => {
    })
  },

  //保养
  goToMaintain(e){
    let detail=e.currentTarget.dataset.detail;
    let obj={
      repertoryId: detail.id
    }
    wx.navigateTo({
      url: "/packageA/pages/equipmentMaintainList/equipmentMaintainList?paramObj="+JSON.stringify(obj)
    })
  },
  
  //详情
  goToDetail(e){
    let detail=e.currentTarget.dataset.detail;
    let obj={
      id: detail.id,
      mark: 'detail'
    }
    wx.navigateTo({
      url: "/packageA/pages/equipmentStockDetail/equipmentStockDetail?paramObj="+JSON.stringify(obj)
    })
  },

  //验收
  goToAccept(e){
    let detail=e.currentTarget.dataset.detail;
    let obj={
      id: detail.id,
      mark: 'check'
    }
    wx.navigateTo({
      url: "/packageA/pages/equipmentStockDetail/equipmentStockDetail?paramObj="+JSON.stringify(obj)
    })
  },

  //完成
  onComplete(e){
    Dialog.confirm({
      title: '是否进行完成操作？',
      message:'完成操作后，\n设备状态更新为已完成',
      confirmButtonText:'确定',
      cancelButtonText:'取消'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        className:'repertory',
        data:{
          id: detail.id,
          state: 4,
          finishTime: util.timeFormat(new Date())
        }
      }

      CommonService.goSave(param).then(res=>{       
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('操作成功');
          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败，请联系管理员');
        }
      }).catch((error) => {
        Toast.fail('操作失败，请联系管理员');
      })

    }).catch(() => {
    });
  },

  //检测
  goToCheck(e){
    let detail=e.currentTarget.dataset.detail;
    let obj={
      equipmentNo: detail.equipmentNo ? detail.equipmentNo : null,
      repertoryId: detail.id
    }
    wx.navigateTo({
      url: "/packageA/pages/equipmentCheckList/equipmentCheckList?paramObj="+JSON.stringify(obj)
    })
  },

  //作废
  onVoid(e){
    Dialog.confirm({
      title: '确定要作废当前库存吗',
      confirmButtonText:'确定',
      cancelButtonText:'不作废了'
    }).then(() => {
      let detail=e.currentTarget.dataset.detail;

      let param={
        className:'repertory',
        data:{
          id: detail.id,
          validState: 0
        }
      }

      CommonService.goSave(param).then(res=>{       
        if (res.statusCode == 200 && res.data.success == true){
          Toast.success('已作废');
          setTimeout(() => {
            this.refreshListAndPage();
          }, 1000);
        }else{
          Toast.fail('操作失败');
        }
      }).catch((error) => {
        Toast.fail('操作失败');
      })

    }).catch(() => {
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})